<template>
  <div>
    <vm-status v-if="showStatus"
               empty-text="没有项目数据"
               :type="isError ? 'error' : 'empty'"></vm-status>

    <wxc-tab-page ref="wxc-tab-page"
                  :tab-titles="tabTitles"
                  :tab-styles="tabStyles"
                  :tab-page-height="tabPageHeight"
                  title-type="text"
                  wrap-bg-color="#ffffff"
                  @wxcTabPageCurrentTabSelected="handleTabSelected">

      <image class="account-skeleton"
             v-if="initStatus"
             src="bmlocal://assets/account/skeleton_account_edit.png"></image>
      <div></div>

      <list class="scroller-wrap"
            :style="{paddingBottom: 0}">
        <cell v-for="(cates, index) in outCategoryCols"
              :key="index">
          <div class="account-wrap">
            <wxc-pan-item v-for="(cate, k) in cates"
                          :key="k"
                          ext-id="k"
                          class="account-item"
                          :class="[outSelectIndex===cate.cateIndex?'account-item-active':'']"
                          :style="{width: colWidth, height: colHeight}"
                          @wxcPanItemPan="wxcPanItemPan"
                          @wxcPanItemClicked="handleCateSelected(cate.cateIndex, cate.isEmpty)">
              <image class="account-icon"
                     :src="cate.icon"
                     :style="{marginLeft: iconMarginLeft}"></image>
              <text class="account-text">{{cate.project_des}}</text>
            </wxc-pan-item>
          </div>
        </cell>
        <cell>
          <wxc-pan-item @wxcPanItemPan="wxcPanItemPan">
            <div :style="{width: 750, height: outLeftHeightCalcBoard}"></div>
          </wxc-pan-item>
        </cell>
      </list>

      <list class="scroller-wrap">
        <cell v-for="(cates, index) in inCategoryCols"
              :key="index">
          <div class="account-wrap">
            <wxc-pan-item v-for="(cate, k) in cates"
                          :key="k"
                          ext-id="k"
                          class="account-item"
                          :class="[inSelectIndex===cate.cateIndex?'account-item-active':'']"
                          :style="{width: colWidth, height: colHeight}"
                          @wxcPanItemPan="wxcPanItemPan"
                          @wxcPanItemClicked="handleCateSelected(cate.cateIndex, cate.isEmpty)">
              <image class="account-icon"
                     :src="cate.icon"
                     :style="{marginLeft: iconMarginLeft}"></image>
              <text class="account-text">{{cate.project_des}}</text>
            </wxc-pan-item>
          </div>
        </cell>
        <cell>
          <wxc-pan-item @wxcPanItemPan="wxcPanItemPan">
            <div :style="{width: 750, height: inLeftHeightCalcBoard}"></div>
          </wxc-pan-item>
        </cell>
      </list>
    </wxc-tab-page>

    <!-- <wxc-popup :show="inputVisible"
               ref="inputPopup"
               @wxcPopupOverlayClicked="handleBeforeClose"
               pos="bottom"
               popup-color="#F1F2F3"
               :overlayCfg="overlayCfg"
               :animation="animation"
               :height="virtualKeyboardVisible?492:92"> -->

    <div v-if="inputVisible"
         ref="v-keyboard"
         class="v-keyboard"
         :style="{height:`${virtualKeyboardHeight}px`, bottom: `${-keyboardHeight}px`}">
      <div class="keyboard-remark"
           :style="{height: `${keyboardInputHeight}px`}">
        <div class="flex-row px-3 py-3 flex align-items-center">
          <text class="icon input-remark">&#xe896; 备注:</text>
          <input type="text"
                 placeholder="点击填写备注"
                 v-model="inputRemark"
                 class="input flex"
                 @focus="handleFocus"
                 @blur="handleBlur" />
        </div>
        <text class="input-value">{{inputValue || '0.00'}}</text>
      </div>
      <div v-if="virtualKeyboardVisible">
        <div class="keyboard-row">
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', 7)">7</text>
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', 8)">8</text>
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', 9)">9</text>
          <div class="keyboard"
               @click="handleKeydown('date')">
            <text class="icon"
                  v-if="isToday">&#xe65e; 今天</text>
            <text v-else
                  class="text-primary">{{inputDate}}</text>
          </div>
        </div>
        <div class="keyboard-row">
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', 4)">4</text>
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', 5)">5</text>
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', 6)">6</text>
          <text class="keyboard"
                @click="handleKeydown('op', '+')">+</text>
        </div>
        <div class="keyboard-row">
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', 1)">1</text>
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', 2)">2</text>
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', 3)">3</text>
          <text class="keyboard"
                @click="handleKeydown('op', '-')">-</text>
        </div>
        <div class="keyboard-row">
          <text class="keyboard keyboard-br"
                @click="handleKeydown('dot', '.')">.</text>
          <text class="keyboard keyboard-br"
                @click="handleKeydown('num', '0')">0</text>
          <text class="keyboard keyboard-br keyboard-lg icon"
                @click="handleKeydown('del')">&#xe610;</text>
          <text v-if="needToCalc"
                class="keyboard keyboard-action bg-accent"
                @click="calcValue">=</text>
          <text v-else
                class="keyboard keyboard-action bg-accent"
                :class="[saveLoading&&'btn-disabled']"
                @click="handleKeydown('submit')">完成</text>
        </div>
      </div>
    </div>

    <!-- </wxc-popup> -->

  </div>
</template>
<script>
import { WxcTabPage, Utils, WxcPopup, WxcPanItem, BindEnv } from 'weex-ui'
import { getStyles } from '../../plugins/tab-page-styles'
import { STORAGE_FARM, STORAGE_USER, EVENT_GET_ACCOUNT_RECORD } from '../../plugins/constant'
import { calcNumber } from '../../plugins/utils'
import { groupByCols } from './convert'
import VmStatus from '../../components/vm-status.vue'

const animation = weex.requireModule('animation')

export default {
  components: {
    WxcTabPage,
    WxcPopup,
    VmStatus,
    WxcPanItem
  },
  props: {},
  data() {
    return {
      tabTitles: [
        { title: '支出' },
        { title: '收入' }
      ],
      tabStyles: getStyles({
        width: 200,
        leftOffset: 175,
        normalBottomColor: '#ffffff'
      }),
      tabPageHeight: 1334,
      saveLoading: false,
      isError: false,
      initStatus: true,
      isEmpty: false,

      farm: {},
      user: {},
      servicer: {},
      record: {},

      inCategory: [],
      outCategory: [],
      inSelectIndex: -1,
      outSelectIndex: -1,
      tabIndex: 0, // 0 支出 1 收入

      cols: 5,
      colHeight: 190,
      keyboardInputHeight: 100,
      outLeftHeight: 0, // 空白高度
      inLeftHeight: 0,

      inputVisible: false,
      // overlayCfg: {
      //   hasAnimation: true,
      //   timingFunction: ['ease-in', 'ease-out'],
      //   duration: 150,
      //   opacity: 0.3
      // },
      // animation: {
      //   timingFunction: 'ease-in',
      //   duration: 100
      // },

      inputValue1: '',
      inputValue2: '',
      inputOperate: '',

      inputRemark: '',
      inputDate: '',
      nowDate: '',
      virtualKeyboardVisible: true
    }
  },
  computed: {
    colWidth() {
      return 750 / this.cols
    },
    iconMarginLeft() {
      return (this.colWidth - 80) / 2
    },
    keyboardHeight() {
      return this.keyboardInputHeight * 5
    },
    virtualKeyboardHeight() {
      return this.virtualKeyboardVisible ? this.keyboardHeight : this.keyboardInputHeight
    },

    // 空白高度
    inLeftHeightCalcBoard() {
      return this.inputVisible
        ? this.keyboardHeight + Math.max(0, this.inLeftHeight - this.keyboardHeight)
        : this.inLeftHeight
    },
    outLeftHeightCalcBoard() {
      return this.inputVisible
        ? this.keyboardHeight + Math.max(0, this.outLeftHeight - this.keyboardHeight)
        : this.outLeftHeight
    },

    // 按列分组
    outCategoryCols() {
      return groupByCols(this.outCategory, this.cols)
    },
    inCategoryCols() {
      return groupByCols(this.inCategory, this.cols)
    },
    isToday() {
      return this.nowDate === this.inputDate
    },
    inputValue() {
      return `${this.inputValue1}${this.inputOperate}${this.inputValue2}`
    },
    needToCalc() {
      return !!this.inputOperate
    },
    //
    showStatus() {
      return !this.initStatus && (this.isEmpty || this.isError)
    }
  },
  watch: {},
  created() {
    this.nowDate = this.$utils.dateFormat(new Date(), 'yyyy/MM/dd')
    this.inputDate = this.nowDate

    this.tabPageHeight = Utils.env.getPageHeight()

    this.getFarm()
  },
  mounted() { },
  methods: {
    wxcPanItemPan(e) {
      if (BindEnv.supportsEBForAndroid()) {
        this.$refs['wxc-tab-page'].bindExp(e.element)
      }
    },
    getFarm() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      this.user = this.$storage.getSync(STORAGE_USER) || {}
      if (this.farm.id && this.user.userId) {
        this.getParams()
      } else {
        this.initStatus = false
        this.$notice.toast({ message: '您还没有鸡场' })
        this.$router.back()
      }
    },
    getParams() {
      this.$router.getParams().then(res => {
        this.record = (res && res.record) || {}
        this.getServicer()
      }).catch(() => {
        this.initStatus = false
      })
    },
    // 获取龙头企业，以和PC关联
    getServicer() {
      this.$api.getData({
        server: 'agr_chain',
        table: 'supplier_related_view_for_app',
        params: {
          'supplier_id.eq': this.farm.id
        },
        errorMsg: '获取龙头企业数据失败'
      }).then(res => {
        this.isError = false
        const data = res || []
        this.servicer = data[0] || {}
        this.getCategory()
      }).catch(err => {
        this.isError = true
        this.initStatus = false
      })
    },
    getCategory() {
      let orgId = 'SYSTEM'
      if (this.servicer.service_id) {
        orgId += `,${this.servicer.service_id}`
      }

      this.$api.getData({
        server: 'agr_chain',
        table: 'account_project_detail',
        params: {
          'submit_org_id.in': orgId,
          link: 'account_project'
        },
        order: {
          'create_time': 'desc'
        },
        errorMsg: '获取收支分类失败'
      }).then(res => {
        const data = res || []
        this.isEmpty = !data.length

        const inCategory = []
        const outCategory = []
        for (const d of data) {
          if (+d.project_type === 1) {
            inCategory.push(d)
          } else {
            outCategory.push(d)
          }
        }

        // 为了全屏左右切换，添加一些空白的项目
        // 只添加当前的，剩余高度用一个空白wxcPanItem来撑满
        this.injectEmptyItem(inCategory)
        this.injectEmptyItem(outCategory)

        // 计算空白高度
        this.inLeftHeight = Math.max(0, this.tabPageHeight - Math.ceil(inCategory.length / this.cols) * this.colHeight)
        this.outLeftHeight = Math.max(0, this.tabPageHeight - Math.ceil(outCategory.length / this.cols) * this.colHeight)

        this.inCategory = inCategory
        this.outCategory = outCategory

        this.initEditData()
      }).finally(() => {
        this.initStatus = false
      })
    },
    injectEmptyItem(list) {
      const rowLeft = list.length % this.cols
      if (rowLeft > 0) {
        for (let i = rowLeft; i < this.cols; i++) {
          list.push({
            isEmpty: true,
            project_des: ' '
          })
        }
      }
    },

    // 编辑的时间初始化数据
    initEditData() {
      if (!this.record.id) {
        return
      }

      const {
        account_record_type: rType,
        project_detail_id: rId,
        account_funds: rFunds,
        remark: rRemark,
        account_date: rDate
      } = this.record

      // tab页
      const isIn = +rType === 1
      this.tabIndex = isIn ? 1 : 0
      this.$refs['wxc-tab-page'].setPage(this.tabIndex, null, false)

      // 项目选择
      const list = isIn ? this.inCategory : this.outCategory
      const index = list.findIndex((item, index) => item.id === rId)
      if (index < 0) { return }
      this.handleCateSelected(index, false)

      // 金额、备注、日期
      this.inputValue1 = rFunds
      this.inputRemark = rRemark
      this.inputDate = (rDate || '').substr(0, 10).replace(/-/g, '/')
    },

    handleTabSelected(e) {
      this.tabIndex = e.page
    },
    handleCateSelected(index, isEmpty) {
      if (isEmpty) {
        return
      }

      if (this.tabIndex === 0) {
        this.inSelectIndex = -1
        this.outSelectIndex = index
      } else {
        this.inSelectIndex = index
        this.outSelectIndex = -1
      }

      if (!this.inputVisible) {
        this.inputVisible = true
        setTimeout(() => {
          this._animateKeyboardShow()
        }, 50)
      }
    },
    handleBeforeClose() {
      this.inputVisible = false
    },

    handleSumbit() {
      if (this.saveLoading) {
        return
      }

      const value = Number.parseFloat(this.inputValue1) || 0
      if (!value) {
        return this.$notice.toast({ message: '请输入金额' })
      }

      const projectItem = this.tabIndex === 0
        ? this.outCategory[this.outSelectIndex]
        : this.inCategory[this.inSelectIndex]

      const data = {
        account_date: this.inputDate.replace(/\//g, '-'),
        account_funds: this.inputValue1,
        account_record_type: this.tabIndex === 0 ? 2 : 1,
        farm_id: this.farm.id,
        project_detail_des: projectItem.project_des,
        project_detail_id: projectItem.id,
        project_id: projectItem.project_id,
        project_name: projectItem.project_value,
        remark: this.inputRemark,
        submit_person: this.user.userId
      }

      const serviceId = this.servicer.service_id
      if (serviceId) {
        data.service_id = serviceId
      }

      const id = this.record.id
      if (id) {
        this.updateData(id, data)
      } else {
        this.addData(data)
      }
    },
    async updateData(id, data) {
      this.saveLoading = true
      const [res] = await this.$utils.pm(this.$api.updateData({
        server: 'agr_chain',
        table: 'account_record_detail',
        id,
        data,
        errorMsg: '修改记账失败'
      }))
      this.saveLoading = false
      if (!res) { return }
      this.onSuccess('修改记账成功')
    },
    async addData(data) {
      this.saveLoading = true
      const [res] = await this.$utils.pm(this.$api.addData({
        server: 'agr_chain',
        table: 'account_record_detail',
        data,
        errorMsg: '添加记账失败'
      }))
      this.saveLoading = false
      if (!res) { return }
      this.onSuccess('添加记账成功')
    },
    onSuccess(message = '提交成功') {
      this.$event.emit(EVENT_GET_ACCOUNT_RECORD, {})
      this.$notice.toast({ message })
      this.$router.setBackParams({ type: 1 })
      this.$router.back()
    },

    handleFocus() {
      this.virtualKeyboardVisible = false
    },
    handleBlur() {
      this.virtualKeyboardVisible = (true && this.inputVisible)
    },
    handleKeydown(type, value) {
      switch (type) {
        case 'date':
          this.$dialog.datePick({
            initialDate: this.inputDate.replace(/\//g, '-'),
            type: 0,
            onPositive: res => {
              const { year, month, day } = res
              this.inputDate = `${year}/${month}/${day}`
            }
          })
          break
        case 'del':
          if (this.inputValue2) {
            this.inputValue2 = this.deleteLastChar(this.inputValue2)
          } else if (this.inputOperate) {
            this.inputOperate = ''
          } else if (this.inputValue1) {
            this.inputValue1 = this.deleteLastChar(this.inputValue1)
          }
          break
        case 'op':
          if (this.inputValue2) {
            this.calcValue()
          }
          this.inputOperate = value
          break
        case 'submit':
          this.handleSumbit()
          break
        case 'dot':
          if (this.inputOperate) {
            this.setInputDotValue('inputValue2', value)
          } else {
            this.setInputDotValue('inputValue1', value)
          }
          break
        case 'num':
          if (this.inputOperate) {
            this.setInputValue('inputValue2', value)
          } else {
            this.setInputValue('inputValue1', value)
          }
        default:
          break
      }
    },
    calcValue() {
      const value1 = Number.parseFloat(this.inputValue1) || 0
      const value2 = Number.parseFloat(this.inputValue2) || 0
      let value = 0
      if (this.inputOperate === '+') {
        value = calcNumber(value1 + value2)
      } else if (this.inputOperate === '-') {
        value = calcNumber(value1 - value2)
      }
      this.inputValue1 = `${value}`
      this.inputValue2 = ''
      this.inputOperate = ''
    },
    deleteLastChar(value) {
      return value.replace(/.$/, '')
    },
    setInputValue(key, value) {
      let oldValue = this[key]
      if (oldValue.indexOf('.') > -1) {
        let [, valDec = ''] = oldValue.split('.')
        if (valDec.length >= 2) { value = '' }
      } else if (oldValue === '0') {
        oldValue = ''
      } else if (oldValue.length >= 8) {
        value = ''
      }
      this.$set(this, key, oldValue + value)
    },
    setInputDotValue(key, value) {
      let oldValue = this[key]
      if (oldValue.indexOf('.') > -1) {
        return
      } else {
        this.$set(this, key, oldValue + value)
      }
    },
    _animateKeyboardShow() {
      const containerEl = this.$refs[`v-keyboard`]
      if (!containerEl) {
        return
      }
      animation.transition(containerEl, {
        styles: {
          transform: `translateY(${-this.keyboardHeight}px)`
        },
        duration: 300,
        timingFunction: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
        delay: 0
      }, () => { })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.icon {
  font-family: alicon;
}
.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.justify-content-center {
  justify-content: center;
}
.align-items-center {
  align-items: center;
}

.text-primary {
  color: $primary;
}
.text-muted {
  color: #999;
}
.text-gray {
  color: #666;
}
.p-3 {
  padding: 15px;
}
.px-3 {
  padding-left: 15px;
  padding-right: 15px;
}
.pb-3 {
  padding-bottom: 15px;
}
.pt-3 {
  padding-top: 15px;
}
.py-2 {
  padding-top: 10px;
  padding-bottom: 10px;
}
.py-3 {
  padding-top: 15px;
  padding-bottom: 15px;
}

.bg-accent {
  background-color: $accent;
}
.bg-white {
  background-color: #fff;
}

.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}

.account-skeleton {
  width: 750px;
  height: 725px;
}

.scroller-wrap {
  width: 750px;
  background-color: #fff;
  padding-top: 2px;
  padding-bottom: 2px;
}
.account-wrap {
  width: 750px;
  justify-content: flex-start;
  flex-direction: row;
  flex-wrap: wrap;
}
.account-item {
  position: relative;
  // 这里加padding后，在padding中滑动不会触发切换效果
  // padding-left: 15px;
  // padding-right: 15px;
  // padding-top: 30px;
  // padding-bottom: 30px;
  // align-items: center;
  border-width: 2px;
  border-color: transparent;
}
.account-item-active {
  border-color: $accent;
}

.account-icon {
  width: 80px;
  height: 80px;
  margin-top: 30px;
  margin-bottom: 10px;
}
.account-text {
  font-size: 28px;
  text-align: center;
  flex: 1;
  margin-bottom: 30px;
  lines: 2;
}

.input {
  flex: 1;
  height: 60px;
  font-size: 28px;
  tint-color: #999;
  text-align: left;
}
.input-remark {
  font-size: 28px;
  margin-right: 10px;
}
.input-value {
  font-size: 42px;
  margin-right: 20px;
}

.keyboard-row {
  flex-direction: row;
}
.keyboard {
  flex: 1;
  padding: 10px;
  height: 100px;
  line-height: 80px;
  text-align: center;
  align-items: center;
  justify-content: center;
  border-bottom-color: $border-color;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  font-size: 36px;
}
.keyboard:active {
  background-color: #cccccc;
}
.keyboard-action:active {
  background-color: darken($accent, 10%);
}
.keyboard-lg {
  font-size: 50px;
}
.keyboard-br {
  border-right-color: $border-color;
  border-right-width: 1px;
  border-right-style: solid;
}
.btn-disabled {
  background-color: $gray-600;
  color: #666;
}

.v-keyboard {
  width: 750px;
  position: absolute;
  bottom: 0;
  background-color: #fff;
  box-shadow: 0 0 6px rgba(128, 128, 128, 0.3);
}
.keyboard-remark {
  flex-direction: row;
  align-items: center;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
  border-bottom-style: solid;
  border-top-width: 1px;
  border-top-color: $border-color;
  border-top-style: solid;
  // background-color: #fff;
}
</style>
